package com.qianfeng.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.qianfeng.shopping.dao.LogLoginDao;
import com.qianfeng.shopping.dao.LogLoginDaoImp;
import com.qianfeng.shopping.entity.Account;
import com.qianfeng.shopping.entity.LogLogin;
import com.qianfeng.shopping.service.AccountService;
import com.qianfeng.shopping.service.AccountServiceImp;
import com.qianfeng.shopping.util.GetTime;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet(name = "AccountServlet", value = "/AccountServlet")
public class AccountServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //  request.setCharacterEncoding("utf-8");
        // 获取参数
        String flag = request.getParameter("flag");
        String accountName = request.getParameter("accountName");
        String accountPwd = request.getParameter("accountPwd");
        String accountId =request.getParameter("accountId");
        // 封装属性到对象中
        Account account = new Account();
        account.setAccountName(accountName);
        account.setAccountPwd(accountPwd);
        //  调用业务逻辑层
        AccountService accountService = new AccountServiceImp();
        if("login".equals(flag)){
            Account accountLogin = accountService.login(account);
            System.out.println(accountLogin);
            if (accountLogin == null) {
                request.setAttribute("msg","用户名或者密码错误");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }else{
                // 获取Session  从request对象中getSession()
                HttpSession session= request.getSession();
                // 登录成功以后 记录登录履历
                LogLoginDao dao = new LogLoginDaoImp();
                LogLogin logLogin = new LogLogin();
                logLogin.setLogLoginIp(request.getRemoteAddr());
                logLogin.setLogLoginTime(GetTime.getNow("yyyyMMddHHmmssSSS"));
                logLogin.setAccountId(accountLogin.getAccountId());
               dao.insert(logLogin);
                // 上下文 在服务器中  服务器启动时候就会创建该对象
                ServletContext sc = request.getServletContext();
               // 查询是否含有登录次数
                if (sc.getAttribute("loginTimes") == null) {
                    // 查询登录次数
                    int loginTimes = dao.selectLoginTimes();
                    sc.setAttribute("loginTimes",loginTimes);
                }else{
                    Integer times = (Integer)sc.getAttribute("loginTimes");
                    times+=1;
                    sc.setAttribute("loginTimes",times);
                }
//                session.setAttribute("loginTimes",loginTimes);

//                HttpSession session1= request.getSession(boolean flag);
                // 无参或者true  表示如果没有session  创建新的    参数是false 没有session返回null
                //  利用操作属性方法
                session.setAttribute("account",accountLogin);
                System.out.println("session id="+session.getId());
                System.out.println(session.isNew());

                //  设置session最大的非活动时间  5分钟  到了时间 服务器自动销毁
                session.setMaxInactiveInterval(60*5);
//                session.invalidate(); 让session对象失效
                // 成功跳到主页
//                request.setAttribute("account",accountLogin);

                // 创建Cookie用来保存用户名和密码  new Cookie(String name,String value)
                Cookie cname = new Cookie("accountname",accountLogin.getAccountName());
                Cookie cpwd = new Cookie("accountpwd",accountLogin.getAccountPwd());
                //  设置cookie的有效时间  单位是秒
                cname.setMaxAge(60*10);
                cpwd.setMaxAge(60*10);
                // 将Cookie添加到响应体中
                response.addCookie(cname);
                response.addCookie(cpwd);
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }
        }else  if("selectAll".equals(flag)){
                Map<String,Account> map = accountService.selectAll();
                request.setAttribute("map",map);
                request.getRequestDispatcher("account_list.jsp").forward(request,response);
        }else  if("checkName".equals(flag)){
            boolean result = accountService.checkName(accountName);
            // 设置响应格式
            // text/plain ：纯文本格式
            // text/xml ：  XML格式
            // application/json    ： JSON数据格式
//            response.setHeader("Context-type","text/plain,charset=utf-8");
//            PrintWriter pw = response.getWriter();
//            // 最好不要返回false或者error
//            pw.print(result?"ok":"ng");
//            pw.close();
//            response.setHeader("Context-type","text/xml,charset=utf-8");
//            PrintWriter pw = response.getWriter();
//            // 最好不要返回false或者error
//            pw.write("<?xml version=\'1.0\' encoding=\'UTF-8\'?>");
//            pw.write("<response>");
//            pw.write("<msg>");
//            pw.write(result?"ok":"ng");
//            pw.write("</msg>");
//            pw.write("</response>");
//            pw.close();
        }else  if("selectAccount".equals(flag)){
            // 通过id查询员工信息
            Account acc = accountService.selectAccount(accountId);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Context-type","text/plain,charset=utf-8");
            PrintWriter pw = response.getWriter();
            // 把对象转换成JSON格式的字符串发送到前台
            //  利用阿里巴巴提供的fastjson  1版本有bug已经废弃
           String str =  JSON.toJSONString(acc);
            pw.write(str);
            pw.close();
        }else  if("selectAllJson".equals(flag)){
            // 通过id查询员工信息
            Map<String,Account> map = accountService.selectAll();
            response.setCharacterEncoding("utf-8");
            response.setHeader("Context-type","text/plain,charset=utf-8");
            PrintWriter pw = response.getWriter();
            String str =  JSON.toJSONString(map.values());
            pw.write(str);
            pw.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
